/**
 * Vuex 数据容器,实现了组件共享数据,避免了父传子,子传父
 */

import Vue from 'vue'
import Vuex from 'vuex'
import { getItem, setItem, removeItem } from '@/utils/storage.js'

Vue.use(Vuex)

const TOKEN = 'TOUTIAO_USER'
export default new Vuex.Store({
  state: {
    // 用户的登录状态信息
    user: getItem(TOKEN),
    cachePages: ['LayoutIndex']
  },
  mutations: {
    // 将token放入本地存储
    setUser (state, data) {
      state.user = data
      setItem(TOKEN, data)
    },
    // 将token从本地存储中移除
    removeUser (state) {
      state.user = null
      removeItem(TOKEN)
    },
    // 添加缓存页面
    addCachePage (state, pageName) {
      if (!state.cachePages.includes(pageName)) {
        state.cachePages.push(pageName)
      }
    },
    // 移除缓存页面
    removeCachePage (state, pageName) {
      const idx = state.cachePages.indexOf(pageName)
      if (idx !== -1) {
        // console.log(this.state.cachePages === state.cachePages)
        state.cachePages.splice(idx, 1)
      }
    }
  },
  actions: {},
  modules: {}
})
